package com.berry.MedCheck.db;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import com.berry.MedCheck.Utils;

/**
 * Created by Airay.Rong on 13-12-21.
 */
public class DBMonitorService extends Service {
	private int MAX_NUM = 12 * 60 * 6;
	//private int MAX_NUM = 2;
	private Cursor mCursor;
	private long    mCurrentUserID = -1;
	private static final String[] PROJECTION = new String[]{
			UserDB.DBColumns._ID, // 0
			UserDB.DBColumns.USERID, // 2
			UserDB.DBColumns.DATE, // 3
	};
	private static final int MONITOR_WINDOW = 1 * 60 * 60 * 1000;

	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		SharedPreferences sp = getSharedPreferences(Utils.PREFERENCE_NAME, 0);
		mCurrentUserID = sp.getLong(Utils.PRE_KEY_CURRENT_USER_ID, -1);
		if (mCurrentUserID < 0) {
			stopSelf();
			return;
		}

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		queryUserRecords();
		return super.onStartCommand(intent, flags, startId);
	}

	private void queryUserRecords() {
		try {
			String selection = "userid=" + mCurrentUserID;
			mCursor = getContentResolver().query(
					UserDB.DBColumns.MEASURE_URI,            // Use the default content URI for the provider.
					PROJECTION,                       // Return the note ID and title for each note.
					selection,                             // No where clause, return all records.
					null,                             // No where clause, therefore no where column values.
					UserDB.DBColumns.DEFAULT_MEAUSURE_SORT_ORDER  // Use the default sort order.
			);
			int nCount = mCursor.getCount();
			if (nCount == 0 || nCount < MAX_NUM) {
				Log.d(Utils.TAG3, "DBMonitorService No old data need to delete");
				stopSelf();
				return;
			}
			int iid = mCursor.getColumnIndex(UserDB.DBColumns._ID);
			mCursor.moveToFirst();
			int nEndID = mCursor.getInt(iid);
			int nTargedID = nEndID - MAX_NUM;

			String selection2 = "userid=? and _id<=?";
			String[] selectionArgs = {Long.toString(mCurrentUserID), Integer.toString(nTargedID)};
			int num = getContentResolver().delete(UserDB.DBColumns.MEASURE_URI,
					selection2, selectionArgs);
			Log.d(Utils.TAG3, "DBMonitorService " + num + " Old data deleted in Measure db");
			stopSelf();
		} catch (Exception e) {
			e.printStackTrace();
		}


	}
}
